package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.entity.*;
import com.guguskins.back.entity.vo.PageVo;
import com.guguskins.back.entity.vo.TurntableVo;
import com.guguskins.back.mapper.GuTurntableMapper;
import com.guguskins.back.service.*;
import com.guguskins.back.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 转盘表 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-14
 */
@Service
public class GuTurntableServiceImpl extends ServiceImpl<GuTurntableMapper, GuTurntable> implements GuTurntableService {
    @Autowired
    private GuTurntableMapper turntableMapper;
    @Autowired
    private GuGoodsService guGoodsService;
    @Autowired
    private GuBoxService boxService;
    @Autowired
    private GuPropService propService;
    @Autowired
    private GuDiscountService guDiscountService;
    @Autowired
    private GuUserService userService;
    @Autowired
    private GuPrizeRecordService prizeRecordService;
    @Autowired
    private GuSystemConfigService systemConfigService;

    @Override
    public Map<String, Object> selectListTurntable(Integer pageNum, Integer pageSize, Integer userId) {
        PageVo<TurntableVo> pageVo = new PageVo<>();
        List<GuTurntable> guTurntables = turntableMapper.findAllByPage(pageNum, pageSize);
        List<TurntableVo> turntableVos = new ArrayList<>();
        GuUser user = userService.getById(userId);
        guTurntables.forEach(guTurntable -> {
            if (guTurntable.getTtEnable() == 1) {
                TurntableVo turntableVo = new TurntableVo();
                if (guTurntable.getTtPrizeType() == 1) {
                    GuBox box = boxService.getById(guTurntable.getTtPrizeId());
                    System.out.println(box.getBoxName());
                    turntableVo.setItemImage(box.getBoxImageUrl());
                    turntableVo.setItemName(box.getBoxName());
                    turntableVo.setDiscount(guTurntable.getTtProbability());
                    turntableVo.setIteamId(box.getBoxId());

//                    System.out.println(turntableVo.getItemName());
                } else if (guTurntable.getTtPrizeType() == 2) {
                    GuGoods guGoods = guGoodsService.getById(guTurntable.getTtPrizeId());
                    turntableVo.setItemImage(guGoods.getGoodsIconUrl());
                    turntableVo.setItemName(guGoods.getGoodsName());
                    turntableVo.setDiscount(guTurntable.getTtProbability());
                    turntableVo.setIteamId(guGoods.getGoodsId());
                } else if (guTurntable.getTtPrizeType() == 3) {
                    GuProp guProp = propService.getById(guTurntable.getTtPrizeId());
                    turntableVo.setItemImage(guProp.getPropImage());

                    turntableVo.setItemName(guProp.getPropName());
                    turntableVo.setDiscount(guTurntable.getTtProbability());
                    turntableVo.setIteamId(Long.parseLong(guProp.getPropId() + ""));
                } else if (guTurntable.getTtPrizeType() == 4) {
                    GuDiscount guDiscount = guDiscountService.getById(guTurntable.getTtPrizeId());
                    turntableVo.setItemImage(guDiscount.getDcImages());
                    turntableVo.setItemName(guDiscount.getDcTitle());
                    turntableVo.setDiscount(guTurntable.getTtProbability());
                    turntableVo.setIteamId(Long.parseLong(guDiscount.getDcId() + ""));
                }
                turntableVos.add(turntableVo);

            }
            pageVo.setData(turntableVos);
            pageVo.setTotal(turntableMapper.selectCount());
        });
        Map<String, Object> map = new HashMap<>();
        map.put("revolutions", user.getUserRevolutions());
        map.put("turntableVo", pageVo);
        return map;
    }

    @Override
    public Integer insertUserinfoProbability() {
        HashMap<Integer, Integer> hashMap = new HashMap();
        List<GuTurntable> turntables = turntableMapper.selectList(null);
        turntables.forEach(guTurntable -> {
            hashMap.put(guTurntable.getId(), guTurntable.getTtProbability());
        });
        Set<Integer> keySet = hashMap.keySet();
        List<Integer> weights = new ArrayList<>();
        for (Iterator<Integer> it = keySet.iterator(); it.hasNext(); ) {
            Integer weightStr = it.next();
            int weight = hashMap.get(weightStr);
            for (int i = 0; i < weight; i++) {
                weights.add(weightStr);
            }
        }
        int idx = new Random().nextInt(weights.size());
        return weights.get(idx);
    }

    @Override
    public void delect(Integer id) {
        GuTurntable guTurntable = new GuTurntable();
        guTurntable.setTtEnable(0);
        guTurntable.setId(id);
        turntableMapper.updateById(guTurntable);
    }

    @Override
    public GuTurntable findById(Integer id) {
        GuTurntable guTurntable = turntableMapper.selectById(id);

        if (guTurntable.getTtEnable() == 1) {
            if (guTurntable.getTtPrizeType() == 1) {

                guTurntable.setGuBox(boxService.getById(guTurntable.getTtPrizeId()));

            } else if (guTurntable.getTtPrizeType() == 2) {
                guTurntable.setGuGoods(guGoodsService.getById(guTurntable.getTtPrizeId()));

            } else if (guTurntable.getTtPrizeType() == 3) {
                guTurntable.setGuProp(propService.getById(guTurntable.getTtPrizeId()));

            } else if (guTurntable.getTtPrizeType() == 4) {
                guTurntable.setGuDiscount(guDiscountService.getById(guTurntable.getTtPrizeId()));

            }
        }
        return guTurntable;

    }

    @Override
    public void insertInvenToryOrUser(Integer userId, Integer turntableId) {
        GuPrizeRecord prizeRecord = new GuPrizeRecord();
        prizeRecord.setPrTurntableId(turntableId);
        prizeRecord.setPrUserId(userId);
        prizeRecordService.save(prizeRecord);
        userService.updateuserRevolutions(userId);
    }

    @Override
    public PageVo<TurntableVo> findByList(Integer pageNum, Integer pageSize) {
        if (pageNum == 1) {
            pageNum = 0;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        List<GuTurntable> guTurntables = turntableMapper.findAllByPage(pageNum, pageSize);
        List<TurntableVo> turntableVos = new ArrayList<>();

        guTurntables.stream().forEach(guTurntable -> {
            TurntableVo turntableVo = new TurntableVo();
            if (guTurntable.getTtPrizeType() == 1) {
                GuBox box = boxService.getById(guTurntable.getTtPrizeId());
                System.out.println(box.getBoxName());
                turntableVo.setItemImage(box.getBoxImageUrl());
                turntableVo.setItemName(box.getBoxName());
                turntableVo.setDiscount(guTurntable.getTtProbability());
                turntableVo.setIteamId(box.getBoxId());
//                    System.out.println(turntableVo.getItemName());
            } else if (guTurntable.getTtPrizeType() == 2) {
                GuGoods guGoods = guGoodsService.getById(guTurntable.getTtPrizeId());
                turntableVo.setItemImage(guGoods.getGoodsIconUrl());
                turntableVo.setItemName(guGoods.getGoodsName());
                turntableVo.setDiscount(guTurntable.getTtProbability());
                turntableVo.setIteamId(guGoods.getGoodsId());
            } else if (guTurntable.getTtPrizeType() == 3) {
                GuProp guProp = propService.getById(guTurntable.getTtPrizeId());
                turntableVo.setItemImage(guProp.getPropImage());

                turntableVo.setItemName(guProp.getPropName());
                turntableVo.setDiscount(guTurntable.getTtProbability());
                turntableVo.setIteamId(Long.parseLong(guProp.getPropId() + ""));
            } else if (guTurntable.getTtPrizeType() == 4) {
                GuDiscount guDiscount = guDiscountService.getById(guTurntable.getTtPrizeId());
                turntableVo.setItemImage(guDiscount.getDcImages());
                turntableVo.setItemName(guDiscount.getDcTitle());
                turntableVo.setDiscount(guTurntable.getTtProbability());
                turntableVo.setIteamId(Long.parseLong(guDiscount.getDcId() + ""));
            }
            turntableVo.setId(guTurntable.getId());
            turntableVo.setEnable(guTurntable.getTtEnable());
            turntableVo.setTtOpenDoor(guTurntable.getTtOpenDoor());
            turntableVo.setTtType(guTurntable.getTtType());
            turntableVos.add(turntableVo);
        });


        return new PageVo<>(turntableVos, turntableMapper.selectCount());
    }

    /**
     * 每日奖励抽奖次数限制
     */
    @Override
    public int luckyDrawLimit(Long userId, BigDecimal money) {
        GuUser user = userService.getById(userId);
        if (user != null) {
            boolean b = RedisUtil.hasKey("frequency:" + userId);
            boolean m = RedisUtil.hasKey("money:" + userId);
            GuSystemConfig systemConfig = systemConfigService.getSystemConfig();
            if (m) {
                BigDecimal moneyR = new BigDecimal(RedisUtil.getValue("money:" + userId));
                BigDecimal count = moneyR.add(money);
                BigDecimal mMoney = systemConfig.getConfigTurntableAmount();
                if (count.compareTo(mMoney) >= 0) {
                    int fre = count.divide(mMoney, BigDecimal.ROUND_HALF_UP).intValue();
                    if (b) {
                        Integer rFrequency = Integer.parseInt(RedisUtil.getValue("frequency:" + userId));
                        Integer mFreQuency = systemConfig.getConfigTurntableLimit();
                        fre = rFrequency + fre;
                        if (fre > mFreQuency) {
                            RedisUtil.setKey("frequency:" + userId, mFreQuency + "");
                            //抽奖次数到上限保存的是规定的次数
                            user.setUserRevolutions(mFreQuency);
                            userService.updateById(user);
                            return 0;
                        } else {
                            RedisUtil.setKey("frequency:" + userId, fre + "");
                            //保存成功
                            user.setUserRevolutions(fre);
                            userService.updateById(user);
                            return 1;
                        }
                    } else {

                        Integer mFreQuency = systemConfig.getConfigTurntableLimit();
                        if (fre > mFreQuency) {
                            RedisUtil.setKey("frequency:" + userId, mFreQuency + "");
                            user.setUserRevolutions(mFreQuency);

                            //抽奖次数到上限
                            // 保存的是规定的次数
                            userService.updateById(user);
                            return 0;
                        } else {
                            RedisUtil.setKey("frequency:" + userId, fre + "");
                            user.setUserRevolutions(fre);
                            //保存成功
                            userService.updateById(user);
                            return 1;
                        }
                    }

                }
                RedisUtil.setKey("money:" + userId, count + "");
            } else {

                BigDecimal mMoney = systemConfig.getConfigTurntableAmount();
                if (money.compareTo(mMoney) >= 0) {
                    int fre = money.divide(mMoney, BigDecimal.ROUND_HALF_UP).intValue();
                    if (b) {
                        Integer rFrequency = Integer.parseInt(RedisUtil.getValue("frequency:" + userId));

                        Integer mFreQuency = systemConfig.getConfigTurntableLimit();
                        fre = rFrequency + fre;
                        if (fre >= mFreQuency) {
                            RedisUtil.setKey("frequency:" + userId, mFreQuency + "");
                            user.setUserRevolutions(mFreQuency);
                            //抽奖次数到上限保存的是规定的次数
                            userService.updateById(user);
                            return 0;
                        } else {
                            RedisUtil.setKey("frequency:" + userId, fre + "");
                            user.setUserRevolutions(fre);
                            //保存成功
                            userService.updateById(user);
                            return 1;
                        }
                    } else {

                        Integer mFreQuency = systemConfig.getConfigTurntableLimit();
                        if (fre > mFreQuency) {

                            RedisUtil.setKey("frequency:" + userId, mFreQuency + "");
                            user.setUserRevolutions(mFreQuency);
                            //抽奖次数到上限
                            // 保存的是规定的次数
                            userService.updateById(user);
                            return 0;
                        } else {

                            RedisUtil.setKey("frequency:" + userId, fre + "");
                            user.setUserRevolutions(fre);
                            //保存成功
                            userService.updateById(user);
                            return 1;
                        }
                    }

                }
                RedisUtil.setKey("money:" + userId, money + "");
            }
            //操作失败
            return 2;

        }
        //没有该用户
        return 3;
    }
}
